package com.kylin.module.shop.actions;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.criterion.Order;

import com.kylin.common.Constants;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.entity.MsgKey;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.paginate.DisplayPage;
import com.kylin.common.paginate.PageManager;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.shop.business.CompanyBlogic;
import com.kylin.module.shop.forms.AdvisoryForm;
import com.kylin.module.shop.forms.InquiryForm;
import com.kylin.module.shop.forms.OrderForm;
import com.kylin.module.shop.forms.SearchDiskForm;
import com.kylin.module.shop.orm.Company;
import com.kylin.module.shop.orm.Content;
import com.kylin.module.shop.orm.InquiryCar;
import com.kylin.module.shop.orm.Product;
import com.kylin.module.user.orm.User;
import com.kylin.struts.BaseDispatchAction;

/**
 * 产品和贸易信息前端功能的接口
 * @author lzh
 *
 */
public class ShopAction  extends BaseDispatchAction {

	protected static Logger log = Logger.getLogger(ShopAction.class);
	
	/**
	 * 商城首页列表
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward shopList(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("商城首页列表 : "+request.getParameter("searchId"));
		String forward = "shopList";
		int pageSize = 5;// 分页列表的每页行数  
		int pageNum = 1;  // 当前页号
		String searchId = request.getParameter("searchId");
		
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
				List condsList = new LinkedList();
				condsList.add(new PropertyCondition("active", Product.ACTIVE_SHOW,PropertyCondition.OPERATOR_EQ ));
				condsList.add(new PropertyCondition("company.active", Constants.ACTIVE_ON,PropertyCondition.OPERATOR_EQ ));
				String  langcode = null;
				if (getSessionLocale(request) == null){
					langcode = "zh_cn";
				}else{
					langcode = getSessionLocale(request).toString();
				}
				
				condsList.add(new PropertyCondition("language", langcode,PropertyCondition.OPERATOR_EQ ));
				if( hasParam(request.getParameter("name")) ){
					String likeExp = "%"+request.getParameter("name")+"%";
					condsList.add(new PropertyCondition("name",likeExp,PropertyCondition.OPERATOR_LIKE));
				}
				// 产品下拉菜单条件，分为一级分类和二级分类
				if( hasParam(request.getParameter("parentCat")) ){
					Dict parent = (Dict)BaseHibernateDAO.findById(Dict.class,new Long(request.getParameter("parentCat")));
					condsList.add(new PropertyCondition("catproduct.parent",parent,PropertyCondition.OPERATOR_EQ));
					request.setAttribute("searchCatProduct",parent);
				}else if( hasParam(request.getParameter("catproduct"))){
					Long catid = new Long(request.getParameter("catproduct"));
					condsList.add(new PropertyCondition("catproduct.id",catid,PropertyCondition.OPERATOR_EQ));
					request.setAttribute("searchCatProduct",BaseHibernateDAO.findById(Dict.class, catid));
				}
				if( hasParam(request.getParameter("country")) ){
					String country = request.getParameter("country");
					condsList.add(new PropertyCondition("company.user.country",country,PropertyCondition.OPERATOR_EQ));
				}
			    if( hasParam(request.getParameter("catid"))){
				    condsList.add(new PropertyCondition("catproduct.id",new Long(request.getParameter("catid")),PropertyCondition.OPERATOR_EQ ));
					request.setAttribute("searchCatProduct",BaseHibernateDAO.findById(Dict.class,new Long(request.getParameter("catid"))));
			    }
			    if( hasParam(request.getParameter("companyId")))
				    condsList.add(new PropertyCondition("company.id",new Long(request.getParameter("companyId")),PropertyCondition.OPERATOR_EQ ));
				
				PropertyCondition[] array = (PropertyCondition[])condsList.toArray(new PropertyCondition[0]);
				// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
				cinfo = new CriteriaInfo(Product.class, array, Order.desc("lastupdatedon"));
				searchId = this.addUserCacheCriteriaInfo(request, cinfo);
				request.setAttribute(Constants.KEY_REQUEST_QUERYID, searchId);
			}
			cinfo = getUserCacheCriteriaInfo(request, searchId);
			log.debug(" cinfo:  "+cinfo.toString());
			if(cinfo == null)
				throw new BusinessException("长时间未刷新页面，上次查询已失效，请重新访问上个页面");
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		return mapping.findForward(forward);
	}

	
	/**
	 * 公司列表
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward companyList(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("公司列表 : "+request.getParameter("searchId"));
		String forward = "companyList";
		int pageSize = 20;// 分页列表的每页行数  
		int pageNum = 1;  // 当前页号
		String searchId = request.getParameter("searchId");
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
				List condsList = new LinkedList();
				condsList.add(new PropertyCondition("user.active", Constants.ACTIVE_ON,PropertyCondition.OPERATOR_EQ ));
				condsList.add(new PropertyCondition("active", Constants.ACTIVE_ON,PropertyCondition.OPERATOR_EQ ));
				condsList.add(new PropertyCondition("language", getSessionLocale(request).toString(),PropertyCondition.OPERATOR_EQ ));
				if( hasParam(request.getParameter("name")) ){
					String likeExp = "%"+request.getParameter("name")+"%";
					condsList.add(new PropertyCondition("name",likeExp,PropertyCondition.OPERATOR_LIKE));
				}
				 
				if( hasParam(request.getParameter("mainbusiness")) ){
					Dict business = (Dict)BaseHibernateDAO.findById(Dict.class,new Long(request.getParameter("business")));
//					condsList.add(new PropertyCondition("catproduct.parent",business,PropertyCondition.OPERATOR_EQ));
					request.setAttribute("searchCatProduct",business);
				}
				
				
				
				if( hasParam(request.getParameter("country")) ){
					String country = request.getParameter("country");
					condsList.add(new PropertyCondition("user.country",country,PropertyCondition.OPERATOR_EQ));
				}
			    if( hasParam(request.getParameter("language")))
				    condsList.add(new PropertyCondition("language",request.getParameter("language"),PropertyCondition.OPERATOR_EQ ));
				if( hasParam(request.getParameter("catproduct"))){
					Long catId = new Long(request.getParameter("catproduct"));
					Long[]comIds = new CompanyBlogic().getCompanyIdByCatP(catId);
					condsList.add(new PropertyCondition("id",comIds,PropertyCondition.OPERATOR_IN));
					request.setAttribute("searchCatProduct",BaseHibernateDAO.findById(Dict.class, catId));
				}
				
				PropertyCondition[] array = (PropertyCondition[])condsList.toArray(new PropertyCondition[0]);
				// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
				cinfo = new CriteriaInfo(Company.class, array, Order.desc("createdon"));
				searchId = this.addUserCacheCriteriaInfo(request, cinfo);
				request.setAttribute(Constants.KEY_REQUEST_QUERYID, searchId);
			}
			cinfo = getUserCacheCriteriaInfo(request, searchId);
			if(cinfo == null)
				throw new BusinessException("长时间未刷新页面，上次查询已失效，请重新访问上个页面");
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		return mapping.findForward(forward);
	}

	
	/**
	 * 贸易信息列表
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward contentList(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("贸易信息列表 : "+request.getParameter("searchId"));
		String forward = "contentList";
		int pageSize = 20;// 分页列表的每页行数  
		int pageNum = 1;  // 当前页号
		if(request.getParameter("pageSize")!=null){
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		String searchId = request.getParameter("searchId");
		CriteriaInfo cinfo = null;
		try {
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
				List condsList = new LinkedList();
				//condsList.add(new PropertyCondition("company.active", Constants.ACTIVE_ON,PropertyCondition.OPERATOR_EQ ));
				condsList.add(new PropertyCondition("language", getSessionLocale(request).toString(),PropertyCondition.OPERATOR_EQ ));
				if(Content.TYPE_SELL.toString().equals(request.getParameter("searchType")) )
					condsList.add(new PropertyCondition("type", Content.TYPE_SELL,PropertyCondition.OPERATOR_EQ ));
				else if(Content.TYPE_BUY.toString().equals(request.getParameter("searchType")) )
					condsList.add(new PropertyCondition("type", Content.TYPE_BUY,PropertyCondition.OPERATOR_EQ ));
				if( hasParam(request.getParameter("name")) ){
					String likeExp = "%"+request.getParameter("name")+"%";
					condsList.add(new PropertyCondition("title",likeExp,PropertyCondition.OPERATOR_LIKE));
				}
				// 产品下拉菜单条件，分为一级分类和二级分类
				if( hasParam(request.getParameter("parentCat")) ){
					Dict parent = (Dict)BaseHibernateDAO.findById(Dict.class,new Long(request.getParameter("parentCat")));
					condsList.add(new PropertyCondition("catproduct.parent",parent,PropertyCondition.OPERATOR_EQ));
					request.setAttribute("searchCatProduct",parent);
				}else if( hasParam(request.getParameter("catproduct"))){
					Long catid = new Long(request.getParameter("catproduct"));
					condsList.add(new PropertyCondition("catproduct.id",catid,PropertyCondition.OPERATOR_EQ));
					request.setAttribute("searchCatProduct",BaseHibernateDAO.findById(Dict.class, catid));
				}
				if( hasParam(request.getParameter("country")) ){
					String country = request.getParameter("country");
					condsList.add(new PropertyCondition("company.user.country",country,PropertyCondition.OPERATOR_EQ));
				}
			    if( hasParam(request.getParameter("catid")))
				    condsList.add(new PropertyCondition("catproduct.id",new Long(request.getParameter("catid")),PropertyCondition.OPERATOR_EQ ));
			    if( hasParam(request.getParameter("companyId")))
				    condsList.add(new PropertyCondition("company.id",new Long(request.getParameter("companyId")),PropertyCondition.OPERATOR_EQ ));
				
				PropertyCondition[] array = (PropertyCondition[])condsList.toArray(new PropertyCondition[0]);
				// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
				cinfo = new CriteriaInfo(Content.class, array, Order.desc("createdon"));
				searchId = this.addUserCacheCriteriaInfo(request, cinfo);
				request.setAttribute(Constants.KEY_REQUEST_QUERYID, searchId);
			}
			cinfo = getUserCacheCriteriaInfo(request, searchId);
			if(cinfo == null)
				throw new BusinessException("长时间未刷新页面，上次查询已失效，请重新访问上个页面");
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 商家商店首页列表
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward companyShopList(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("商店首页产品列表 : " + request.getParameter("companyId"));
		String forward = "companyShopList";
		int pageSize = 20;// 分页列表的每页行数
		int pageNum = 1; // 当前页号
		CriteriaInfo cinfo = null;
		String searchId = request.getParameter("searchId");
		try {
			Company com = (Company) BaseHibernateDAO.findById(Company.class, new Long(request
					.getParameter("companyId")));
			request.setAttribute("currentCompany", com);
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {

				List condsList = new LinkedList();
				condsList.add(new PropertyCondition("language", getSessionLocale(request)
						.toString(), PropertyCondition.OPERATOR_EQ));
				// condsList.add(new PropertyCondition("active",
				// Product.ACTIVE_SHOW,PropertyCondition.OPERATOR_EQ ));
				condsList.add(new PropertyCondition("company", com, PropertyCondition.OPERATOR_EQ));
				PropertyCondition[] array = (PropertyCondition[]) condsList
						.toArray(new PropertyCondition[0]);
				cinfo = new CriteriaInfo(Product.class, array, Order.desc("createdon"));

				// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
				searchId = this.addUserCacheCriteriaInfo(request, cinfo);
				request.setAttribute(Constants.KEY_REQUEST_QUERYID, searchId);
			}
			cinfo = getUserCacheCriteriaInfo(request, searchId);
			CompanyBlogic blogic = new CompanyBlogic();
			DisplayPage page = blogic.getProductList(pageSize, pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);
		} catch (Exception e) {
			forward = doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 商家商店首页列表
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward companyContentList(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.debug("商店贸易信息列表 : "+request.getParameter("companyId"));
		String forward = "companyContentList";
		int pageSize = 20;// 分页列表的每页行数  
		int pageNum = 1;  // 当前页号
		CriteriaInfo cinfo = null;
		String searchId = request.getParameter("searchId");
		try {
			String type = request.getParameter("type");
			Company com = (Company) BaseHibernateDAO.findById(Company.class, new Long(request.getParameter("companyId")));
			request.setAttribute("currentCompany", com);			
			if (request.getParameter("page") != null) {
				pageNum = Integer.parseInt(request.getParameter("page"));
			}
			if (searchId == null) {
			List condsList = new LinkedList();
			if(type != null)
			    condsList.add(new PropertyCondition("type", new Short(type),PropertyCondition.OPERATOR_EQ ));
		    condsList.add(new PropertyCondition("company",com,PropertyCondition.OPERATOR_EQ ));			
			PropertyCondition[] array = (PropertyCondition[])condsList.toArray(new PropertyCondition[0]);
			cinfo = new CriteriaInfo(Content.class, array, Order.desc("createdon"));
			
			// 将查询条件保存在 CriteriaInfo，加入到用户缓存UserCache,这样翻页查询时不用再次传入条件
			searchId = this.addUserCacheCriteriaInfo(request, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_QUERYID, searchId);
		}
		cinfo = getUserCacheCriteriaInfo(request, searchId);

			
			DisplayPage page = PageManager.getDisplayPage(pageSize, pageNum, cinfo);
			request.setAttribute(Constants.KEY_REQUEST_RESULT, page);			
		}catch (Exception e) {
			forward = doException( request, e,forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 展示产品详情
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward productDetail(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("查看产品详情 : " + request.getParameter("id"));
		String forward = "productDetail";
		CompanyBlogic blogic = new CompanyBlogic();
		try {
			Product p = blogic.getProduct(request.getParameter("id"));
			request.setAttribute(Constants.KEY_REQUEST_RESULT, p);
		} catch (Exception e) {
			forward = doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 展示贸易信息详情
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward contentDetail(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("查看贸易信息详情 : " + request.getParameter("id"));
		String forward = "contentDetail";
		CompanyBlogic blogic = new CompanyBlogic();
		try {
			Content obj = blogic.getContent(request.getParameter("id"));
			request.setAttribute(Constants.KEY_REQUEST_RESULT, obj);
		} catch (Exception e) {
			forward = doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}

	/**
	 * 订购产品，保存订单
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward buyProduct(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("订购产品 : " + request.getParameter("productId"));
		String forward = "buySucc";
		OrderForm form = (OrderForm)actionForm;
		CompanyBlogic blogic = new CompanyBlogic();
		try {
			blogic.saveOrder(form);
		} catch (Exception e) {
			forward = doException(request, e, "buyfail");
		}
		return mapping.findForward(forward);
	}

	/**
	 * 保存在线咨询信息
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward saveAdvisory(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("保存在线咨询信息 : " + request.getParameter("title"));
		String forward = "saveAdvisory";
		CompanyBlogic blogic = new CompanyBlogic();
		AdvisoryForm form = (AdvisoryForm)actionForm;
		try {
			blogic.saveAdvisory(form);
		} catch (Exception e) {
			forward = doException(request, e, forward);
		}
		return mapping.findForward(forward);
	}
	
	/**
	 * 保存产品询问信息
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward saveInquiry(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		SearchDiskForm form = (SearchDiskForm)actionForm;
			
		log.debug("开始保存产品询问信息"+form.getTitle());
        String[] ids = request.getParameterValues("ids");
        User user = (User)request.getSession().getAttribute(Constants.CURR_USER);
		form.setUserIp(request.getRemoteAddr());
		
		try
		{
			if(ids.length > 0)
			{				
				CompanyBlogic logic = new CompanyBlogic();
				
				for(int i=0;i<ids.length;i++)
				{
					Product p = logic.getProduct(ids[i]);
					logic.saveInquiry(form, p, user);
					
				}
				request.setAttribute(Constants.MSGKEY,new MsgKey("","成功保存信息"));
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		return mapping.findForward("addInquirySucc");
	}
	
	/**
	 * 在session中存放用户对产品批量询问的信息
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward sendInquiry(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("获得客户询问信息保存在session中");
		if(request.getParameterValues("ids") != null)
		{
			InquiryCar inquiryCar = new InquiryCar();
			String[] ids = request.getParameterValues("ids");
			if(request.getSession().getAttribute("inquiryCar") == null)
			{
				for(int i=0;i<ids.length;i++)
				{
					inquiryCar.addInquiry(ids[i]);
				}
				request.getSession().setAttribute("inquiryCar",inquiryCar);
			}
			else if(request.getSession().getAttribute("inquiryCar") != null)
			{
				InquiryCar oldList = (InquiryCar)request.getSession().getAttribute("inquiryCar");
				for(int i=0;i<oldList.getInquiryCar().size();i++)
				{
					String id = (String)oldList.getInquiryCar().get(i);
					inquiryCar.addInquiry(id);
				}
				for(int i=0;i<ids.length;i++)
				{
					inquiryCar.addInquiry(ids[i]);
				}
				request.getSession().setAttribute("inquiryCar",inquiryCar);
			}
		}
		return this.shopList(mapping, actionForm, request, response);
	}

	/**
	 * 查看用户产品询问信息列表
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward listInquiry(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("查看用户产品询问信息列表");	
		String forward = "listInquiry";
		List productList = new ArrayList();
		try
		{
			InquiryCar inquiry = (InquiryCar)request.getSession().getAttribute("inquiryCar");
			if(inquiry != null)
			{
				for(int i=0;i<inquiry.getInquiryCar().size();i++)
				{
					InquiryCar in = new InquiryCar();
					String pId = (String)inquiry.getInquiryCar().get(i);
					CompanyBlogic blogic = new CompanyBlogic();
					Product pro = blogic.getProduct(pId);
					Company com = pro.getCompany();
					User user = com.getUser();
					in.setProduct(pro);
					in.setCompany(com);
					in.setUser(user);
					productList.add(in);
				}
			}
			request.setAttribute(Constants.KEY_REQUEST_RESULT,productList);
		}catch(Exception e)
		{
			doException(request,e,forward);
		}
		return mapping.findForward(forward);
	}
}
